package com.tianyadu.mmall.core.filter;

import com.tianyadu.mmall.core.conf.SecurityConstantsConfig;
import com.tianyadu.mmall.core.conf.ValidateCodeProcessorHolder;
import com.tianyadu.mmall.core.enums.ValidateCodeTypeEnum;
import com.tianyadu.mmall.core.properties.MallSecurityProperties;
import com.tianyadu.mmall.core.validate.code.exception.ValidateCodeException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 校验验证码的过滤器
 *
 * @author xueyj
 * @date 2019-11-05 23:18
 */
@Slf4j
@Component
public class ValidateCodeFilter extends OncePerRequestFilter implements InitializingBean {
    /**
     * 验证码校验失败处理器
     */
    private AuthenticationFailureHandler authFailureHandler;

    /**
     * 系统配置信息
     */
    @Autowired
    private MallSecurityProperties securityProperties;

    /**
     * 系统中的校验码处理器
     */
    @Autowired
    private ValidateCodeProcessorHolder validateCodeProcessorHolder;

    /**
     * 存放所有需要校验验证码的url
     */
    private Map<String, ValidateCodeTypeEnum> urlMap = new HashMap<>();


    /**
     * 验证请求url与配置的url是否匹配的工具类
     */
    private AntPathMatcher pathMatcher = new AntPathMatcher();

    /**
     * 初始化要拦截的url配置信息
     *
     * @throws ServletException
     */
    @Override
    public void afterPropertiesSet() throws ServletException {
        super.afterPropertiesSet();
        /*
        //  需进行验证码校验请求
        String url = securityProperties.getCode().getImage().getUrl();
        //  默认的用户名密码登录请求处理url
        String defaultLoginProcessingUrlForm = SecurityConstantsConfig.DEFAULT_LOGIN_PROCESSING_URL_FORM;
        //  将需要进行验证码校验路径转化为数组
        String[] configUrls = StringUtils.splitByWholeSeparatorPreserveAllTokens(url, ",");
        //  遍历需验证url，并加入urlset中
        for (String configUrl : configUrls) {
            urls.add(configUrl);
        }
        //  将默认的用户名密码登录请求处理url添加至需验证set中
        urls.add(defaultLoginProcessingUrlForm);*/
        //  需图形验证认证请求
        String imageValidateUrl = securityProperties.getCode().getImage().getUrl();
        ValidateCodeTypeEnum image = ValidateCodeTypeEnum.IMAGE;
        //  添加用户名密码登录认证地址及传递参数信息
        urlMap.put(SecurityConstantsConfig.DEFAULT_LOGIN_PROCESSING_URL_FORM, image);
        addUrlToMap(imageValidateUrl, image);

        ValidateCodeTypeEnum sms = ValidateCodeTypeEnum.SMS;
        // 需短信验证认证请求
        String smsValidateUrl = securityProperties.getCode().getSms().getUrl();
        //  添加短信登录认证地址及传递参数信息
        urlMap.put(SecurityConstantsConfig.DEFAULT_LOGIN_PROCESSING_URL_MOBILE, sms);
        addUrlToMap(smsValidateUrl, sms);
    }

    /**
     * 将系统中配置的需要校验验证码的URL根据校验的类型放入map
     *
     * @param urlString
     * @param type
     */
    protected void addUrlToMap(String urlString, ValidateCodeTypeEnum type) {
        if (StringUtils.isNotBlank(urlString)) {
            String[] urls = org.apache.commons.lang.StringUtils.splitByWholeSeparatorPreserveAllTokens(urlString, ",");
            for (String url : urls) {
                urlMap.put(url, type);
            }
        }
    }

    /**
     * 执行过滤器
     * Same contract as for {@code doFilter}, but guaranteed to be
     * just invoked once per request within a single request thread.
     * See {@link #shouldNotFilterAsyncDispatch()} for details.
     * <p>Provides HttpServletRequest and HttpServletResponse arguments instead of the
     * default ServletRequest and ServletResponse ones.
     *
     * @param request
     * @param response
     * @param filterChain
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        ValidateCodeTypeEnum type = getValidateCodeType(request);
        if (type != null) {
            log.info("校验请求({})中的验证码,验证码类型{}", request.getRequestURI(), type);
            try {
                //  根据依赖查找方式，匹配对应处理器，进行安全认证
                validateCodeProcessorHolder.findValidateCodeProcessor(type)
                        .validate(new ServletWebRequest(request, response));
                log.info("验证码校验通过");
            } catch (ValidateCodeException exception) {
                authFailureHandler.onAuthenticationFailure(request, response, exception);
                return;
            }
        }
        filterChain.doFilter(request, response);
    }

    /**
     * 获取校验码的类型，如果当前请求不需要校验，则返回null
     *
     * @param request
     * @return
     */
    private ValidateCodeTypeEnum getValidateCodeType(HttpServletRequest request) {
        ValidateCodeTypeEnum result = null;
        if (!StringUtils.equalsIgnoreCase(request.getMethod(), "get")) {
            Set<String> urls = urlMap.keySet();
            for (String url : urls) {
                if (pathMatcher.match(url, request.getRequestURI())) {
                    result = urlMap.get(url);
                }
            }
        }
        return result;
    }
}